package com.dbkj.axb_group;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dbkj.axb.AxbService;
import com.dbkj.common.model.AxbGroup;
import com.dbkj.common.model.AxbGroupRelation;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.ext.interceptor.Restful;
import com.jfinal.json.Json;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;

import java.util.List;

/**
 * @Author: Max
 * 群
 * @Date: 2019/10/29 9:23
 */


public class AxbGroupController extends Controller {

    @Inject
    AxbGroupService service;

    @Inject
    AxbService axbService;



    /**
     * 群展示
     */
    @Before(Restful.class)
    public void index(){
        Integer pageNumber = getParaToInt("pageNumber");
        Integer pageSize = getParaToInt("pageSize");
        String name = getPara("groupName");
        Page<AxbGroup> page = service.paginate(pageNumber,pageSize,name);
        renderJson(Ret.ok().set("total",page.getTotalRow()).set("rows",JSON.toJSON(page.getList())));
    }


    /**
     * 群删除
     */
    @Before(Restful.class)
    public void delete(){
        Integer id = getParaToInt();
        if(axbService.hasGroup(id)){
            renderError(401, new JsonRender(Ret.by("msg","有绑定的x号码")));
        }else{
            service.delete(id);
            renderJson(Ret.ok());
        }
    }

    /**
     * 群更新
     */
    @Before(Restful.class)
    public void update(){
        AxbGroup group = Json.getJson().parse(getRawData(),AxbGroup.class);
        group.update();
        renderJson(Ret.ok());
    }

    /**
     * 群保存
     */
    @Before(Restful.class)
    public void save(){
        Json.getJson().parse(getRawData(),AxbGroup.class).save();
        renderJson(Ret.ok());
    }

    /**
     * 设置组优先级
     */
    @Before(POST.class)
    public void level(){
        JSONObject object = JSON.parseObject(getRawData());
        Integer groupId = object.getInteger("groupid");
        //首先要把原来的数据删了
        Db.delete("delete from axb_group_relation where group_id =?",groupId);

        JSONArray members = object.getJSONArray("members");
        for(int i=0;i<members.size();i++){
            JSONObject json = members.getJSONObject(i);
            AxbGroupRelation agr = new AxbGroupRelation();
            agr.setGroupId(groupId);
            agr.setLevel(json.getString("level"));
            agr.setRelationId(json.getInteger("aRelationid"));
            agr.save();
        }

        renderJson(Ret.ok());
    }


}
